package br.ufu.facom.pillbox.service;

import java.util.Calendar;
import java.util.List;

import br.ufu.facom.calendar.DateTimeHandler;
import br.ufu.facom.pillbox.activities.HomeActivity;
import br.ufu.facom.pillbox.activities.R;
import br.ufu.facom.pillbox.dao.AgendaDAO;
import br.ufu.facom.pillbox.domain.Agenda;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class NotificationService extends Service implements Runnable {

	public final static String RUN_SERVICE = "br.ufu.facom.pillbox.service.RUN_SERVICE";
	public final static String START_SERVICE = "br.ufu.facom.pillbox.service.START_SERVICE";
	public final static String ITERATE_SERVICE = "br.ufu.facom.pillbox.service.ITERATE_SERVICE";
	public final static String STOP_SERVICE = "br.ufu.facom.pillbox.service.STOP_SERVICE";
	public final static String DEACTIVATE_SERVICE = "br.ufu.facom.pillbox.service.DEACTIVATE_SERVICE";
	final static String PREFS_NAME = " service_control ";
	final static String SERVICE_STATE = "service_state";
	final static String SERVICE_INACTIVE = "service_inactive";
	final static String SERVICE_STOPPED = "service_stopped";
	final static String SERVICE_STARTED = "service_started";
	Thread thread = null;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(this.getClass().getCanonicalName(), "onCreate");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(this.getClass().getCanonicalName(), "onStartCommand");
		SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
		String state = prefs.getString(SERVICE_STATE, SERVICE_STARTED);
		if (state.equals(SERVICE_INACTIVE)
				&& !intent.getAction().equals(START_SERVICE)) {
			Log.i(this.getClass().getCanonicalName(),
					"onStartCommand inactive " + intent.getAction());
			return START_NOT_STICKY;
		}
		if (state.equals(SERVICE_STOPPED)
				&& (intent.getAction().equals(STOP_SERVICE) || intent
						.getAction().equals(ITERATE_SERVICE))) {
			Log.i(this.getClass().getCanonicalName(), "onStartCommand stopped "
					+ intent.getAction());
			return START_NOT_STICKY;
		}
		if (!state.equals(SERVICE_STARTED)
				|| intent.getAction().equals(STOP_SERVICE)
				|| intent.getAction().equals(DEACTIVATE_SERVICE)) {
			Editor editor = prefs.edit();
			if (intent.getAction().equals(STOP_SERVICE)) {
				editor.putString(SERVICE_STATE, SERVICE_STOPPED);
				editor.commit();
				Log.i(this.getClass().getCanonicalName(), "onStartCommand stop");
				return START_NOT_STICKY;
			}
			if (intent.getAction().equals(DEACTIVATE_SERVICE)) {
				editor.putString(SERVICE_STATE, SERVICE_INACTIVE);
				editor.commit();
				Log.i(this.getClass().getCanonicalName(),
						"onStartCommand deactivate");
				return START_NOT_STICKY;
			}
			editor.putString(SERVICE_STATE, SERVICE_STARTED);
			editor.commit();
		}

		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+60000, PendingIntent
				.getService(this, 0, intent.setAction(ITERATE_SERVICE),
						PendingIntent.FLAG_ONE_SHOT));
		if (this.thread != null
				&& (this.thread.isAlive() || this.thread.getState() != Thread.State.TERMINATED))
			Log.i(this.getClass().getCanonicalName(), "onStartCommand not done");
		else {
			this.thread = new Thread(this);
			this.thread.start();
		}
		return START_NOT_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(this.getClass().getCanonicalName(), "onDestroy");
	}

	@Override
	public void run() {
		Log.d(this.getClass().getCanonicalName(), "run");
		AgendaDAO agendaDAO;
		agendaDAO = new AgendaDAO(getApplicationContext());
		Log.d(this.getClass().getCanonicalName(), "openDB");
		agendaDAO.open();
		DateTimeHandler dt = new DateTimeHandler();
		dt.setCalendar(Calendar.getInstance());
		List<Agenda> agendas = agendaDAO
				.getRecentes(dt.getDate(), dt.getTime());
		PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 
				0, new Intent(this, HomeActivity.class), PendingIntent.FLAG_ONE_SHOT);
		for (Agenda agenda : agendas) {
			NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
					this).setContentText(agenda.getMedic()).addAction(0, "Medicamento: " + agenda.getMedic(), pi);
			// Sets an ID for the notification
			int mNotificationId = 001;
			// Gets an instance of the NotificationManager service
			NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			// Builds the notification and issues it.
			mNotifyMgr.notify(mNotificationId, mBuilder.build());
			Log.d(this.getClass().getCanonicalName(),
					"notification " + agenda.getMedic());
			agenda.setDTNot(dt.getDate());
			agenda.setTMNot(dt.getTime());
			agendaDAO.create(agenda);
		}
		Log.d(this.getClass().getCanonicalName(), "closeDB");
		agendaDAO.close();
		stopSelf();
	}
}
